package com.aiyige.page.my.merchandisemanagement.mmlearnvideo.adapter;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ActionEngine;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.base.eventbus.EventEditLearnVideoFinish;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventSelectGuarantee;
import com.aiyige.model.moment.backup.DetailBackup;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.SingleVideo;
import com.aiyige.model.moment.entity.VideoCourse;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.my.merchandisemanagement.MerchandiseManagementPage;
import com.aiyige.page.publish.CommonTipDialog;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.learnvideo.PublishLearnVideoFormPage;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoFormModel;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoItem;
import com.aiyige.page.publish.selectcoursetype.model.CourseTypeItem;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selectlearntarget.model.SelectLearnTargetItem;
import com.aiyige.page.publish.selectsuitablepeople.model.SelectSuitablePeopleItem;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.selectteacher.model.TeacherItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.FontUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.WebImageUrlModifier;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.UpdateBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

/**
 * Created by zhuyakun on 2017/11/22.
 */

public class MMLearnVideoAdapter extends BaseQuickAdapter<LearnVideoModel, BaseViewHolder> {
    CommonBottomDialogFragment publishedItemDialog;
    CommonBottomDialogFragment notPublishedItemDialog;
    CommonBottomDialogFragment inReviewItemDialog;
    CommonBottomDialogFragment rejectItemDialog;
    CommonBottomDialogFragment uploadingItemDialog;
    FragmentActivity mActivity;
    EventBus eventBus;
    int currentPosition;
    TrackEvent trackEvent = new TrackEvent();

    public EventBus getEventBus() {
        return eventBus;
    }


    @Override
    public void onViewAttachedToWindow(BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        try {
            eventBus.register(holder);
        } catch (Exception e) {

        }
    }

    @Override
    public void onViewDetachedFromWindow(BaseViewHolder holder) {
        Timber.e("onViewDetachedFromWindow:");
        try {
            eventBus.unregister(holder);
        } catch (Exception e) {

        }
        super.onViewDetachedFromWindow(holder);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectGuarantee(EventSelectGuarantee event) {
        if (event.getResultCode() == EventSelectGuarantee.RESULT_OK) {
            new SubmitReviewAsyncTask().execute(currentPosition, event.getGuaranteeItemList());
        }
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventEditLearnVideoFinish(EventEditLearnVideoFinish event) {
        if (event.getResultCode() == EventEditLearnVideoFinish.RESULT_OK) {
            if (getItem(currentPosition).getProgressStatus() == PublishUtil.PROGRESS_STATUS_PUBLISHED) {
                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_LEARN_VIDEO_EDIT, TrackEvent.PUBLISH_LEARN_VIDEO_EDIT_LABEL);
            }
            setData(currentPosition, event.getLearnVideoModel());
            Collections.sort(getData(), new Comparator<LearnVideoModel>() {
                @Override
                public int compare(LearnVideoModel o1, LearnVideoModel o2) {
                    long diff = o2.getReleaseDate() - o1.getReleaseDate();
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            notifyDataSetChanged();
        }
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {

        }
    }

    public MMLearnVideoAdapter(final FragmentActivity activity) {
        super(new LinkedList<LearnVideoModel>());
        eventBus = EventBus.builder().build();
        mActivity = activity;
        publishedItemDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_published_item_dialog)
                .viewIdList(Arrays.asList(R.id.cancelBtn, R.id.cancelPublishedBtn, R.id.editBtn, R.id.deleteBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn:
                                new CancelPublishAsyncTask().execute(position);
                                break;
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMLearnVideoAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "0");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteGoodsAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();

        notPublishedItemDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_not_published_item_dialog)
                .viewIdList(Arrays.asList(R.id.cancelBtn, R.id.publishedBtn, R.id.editBtn, R.id.deleteBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.publishedBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMLearnVideoAdapter.this);
                                } catch (Exception e) {

                                }

                                String channel = "";
                                try {
//                                    PublishInterestItem publishInterestItem = JSON.parseObject(getItem(position).getInterestCategory(), PublishInterestItem.class);
//                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.GuaranteePage)
                                        .withString("subject", Moment.SUBJECT_VIDEO_COURSE)
                                        .withBoolean("postEvent", true)
                                        .navigation();
                            {
                                Map<String, String> attrs = new HashMap<>();
                                attrs.put("method", "0");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD, TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD_LABEL, attrs);
                            }

                            break;
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMLearnVideoAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditAsyncTask(mActivity).execute(position);
                            {
                                Map<String, String> attrs = new HashMap<>();
                                attrs.put("method", "1");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD, TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD_LABEL, attrs);
                            }
                            break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "1");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteGoodsAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        inReviewItemDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_inreview_item_dialog)
                .viewIdList(Arrays.asList(R.id.cancelBtn, R.id.deleteBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "2");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteGoodsAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        rejectItemDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_reject_item_dialog)
                .viewIdList(Arrays.asList(R.id.cancelBtn, R.id.editBtn, R.id.rejectReasonBtn, R.id.deleteBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMLearnVideoAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.rejectReasonBtn:
                                CommonTipDialog.newInstance(getItem(position).getRejectReason())
                                        .show(mActivity.getSupportFragmentManager(), "");
                                break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "3");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteGoodsAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        uploadingItemDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_uploading_item_dialog)
                .viewIdList(Arrays.asList(R.id.cancelBtn, R.id.deleteBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn: {
                                final int finalPosition = position;
                                new AlertDialog.Builder(mActivity)
                                        .setTitle(R.string.delete)
                                        .setMessage(R.string.are_you_sure_you_cancel_the_release_of_the_video)
                                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                try {
                                                    TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                                                        @Override
                                                        public Object call() throws Exception {
                                                            LearnVideoModel learnVideoModel = getItem(finalPosition);
                                                            UpdateBuilder<LearnVideoModel, String> updateBuilder = LearnVideoModelDao.getDao().updateBuilder();
                                                            updateBuilder.updateColumnValue(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                                                            updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                                                            updateBuilder.update();
                                                            List<UploadFile> uploadFileList = UploadFileDao.getDao().queryForEq(UploadFile.PARENT_ID_FIELD, learnVideoModel.getId());
                                                            for (UploadFile uploadFile : uploadFileList) {
                                                                UpdateBuilder<UploadFile, Integer> uploadFileUpdateBuilder = UploadFileDao.getDao().updateBuilder();
                                                                uploadFileUpdateBuilder.updateColumnValue(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                                                                uploadFileUpdateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                                                                uploadFileUpdateBuilder.update();
                                                            }
                                                            {
                                                                Map<String, String> attrs = new HashMap<>();
                                                                attrs.put("duration", String.valueOf(System.currentTimeMillis() - learnVideoModel.getReleaseDate()));
                                                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DEL_PUBLISHING_LEARN_VIDEO_DUR, TrackEvent.DEL_PUBLISHING_LEARN_VIDEO_DUR_LABEL, attrs);
                                                            }
                                                            {
                                                                HashMap<String, String> attrs = new HashMap<>();
                                                                attrs.put("status", "1");
                                                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                                            }
                                                            return null;
                                                        }
                                                    });
                                                } catch (SQLException e) {
                                                    Timber.e("onClick:" + Log.getStackTraceString(e));
                                                }
                                                remove(finalPosition);
                                            }
                                        })
                                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .create()
                                        .show();
                                break;
                            }
                        }
                    }
                }).build();


    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(getItemView(R.layout.mmlearn_video_item, parent));
    }

    @Override
    protected void convert(BaseViewHolder helper, LearnVideoModel item) {
        ((ViewHolder) helper).bindData(item);
    }

    public class ViewHolder extends BaseViewHolder {
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.releaseDateTv)
        TextView releaseDateTv;
        @BindView(R.id.freeTv)
        TextView freeTv;
        @BindView(R.id.priceTv)
        TextView priceTv;
        @BindView(R.id.priceLayout)
        LinearLayout priceLayout;
        @BindView(R.id.statusTv)
        TextView statusTv;
        @BindView(R.id.episodeTv)
        TextView episodeTv;
        @BindView(R.id.uploadLayout)
        View uploadLayout;
        @BindView(R.id.uploadStatusIv)
        ImageView uploadStatusIv;
        @BindView(R.id.uploadStatusTv)
        TextView uploadStatusTv;

        LearnVideoModel data;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            FontUtil.setNumberFont(priceTv);
        }

        @OnClick({R.id.moreBtn, R.id.uploadLayout})
        public void onViewClick(View view) {
            switch (view.getId()) {
                case R.id.uploadLayout: {
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            UploadFileDao.resumeByParentId(data.getId());
                            LearnVideoModelDao.resumeById(data.getId());
                            bindData(data);
                            break;
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            UploadFileDao.pauseByParentId(data.getId());
                            LearnVideoModelDao.pauseById(data.getId());
                            bindData(data);
                            break;
                    }
                    break;
                }
                case R.id.moreBtn: {
                    switch (data.getProgressStatus()) {
                        case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                        case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                        case PublishUtil.PROGRESS_STATUS_UPLOADING:
                        case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                        case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                            uploadingItemDialog.setPosition(getAdapterPosition());
                            uploadingItemDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                            notPublishedItemDialog.setPosition(getAdapterPosition());
                            notPublishedItemDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                        case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                            inReviewItemDialog.setPosition(getAdapterPosition());
                            inReviewItemDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                            publishedItemDialog.setPosition(getAdapterPosition());
                            publishedItemDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_REJECT:
                            rejectItemDialog.setPosition(getAdapterPosition());
                            rejectItemDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                    }
                    break;
                }
            }
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onEventPublishProgressStatusUpdate(EventPublishProgressStatusUpdate event) {
            if (!TextUtils.isEmpty(data.getId())) {
                bindData(data);
            }
        }

        public void bindData(LearnVideoModel data) {
            this.data = data;
            if (!TextUtils.isEmpty(data.getId())) {
                try {
                    LearnVideoModelDao.getDao().refresh(data);
                } catch (SQLException e) {
                    Timber.e("onEventPublishProgressStatusUpdate:" + Log.getStackTraceString(e));
                }
            }
            if (data.getControlOption() == PublishUtil.CONTROL_OPTION_DELETE) {
                remove(getAdapterPosition());
                return;
            }
//            if (data.getPrice() < 0.01) {
//                priceLayout.setVisibility(View.INVISIBLE);
//                freeTv.setVisibility(View.VISIBLE);
//            } else {
            freeTv.setVisibility(View.INVISIBLE);
            priceLayout.setVisibility(View.VISIBLE);
            priceTv.setText(StringUtils.priceFormat(data.getPrice()));
//            }
            releaseDateTv.setText(DateFormatUtil.getStandardDate(data.getSellDate()));
            titleTv.setText(Html.fromHtml(data.getTitle()));

            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            uploadStatusIv.setImageResource(R.drawable.upload);
                            uploadStatusTv.setText("");
                            break;
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            uploadStatusIv.setImageResource(R.drawable.suspend);
                            uploadStatusTv.setText("");
                            break;
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                            uploadStatusIv.setImageResource(R.drawable.suspend);
                            uploadStatusTv.setText(R.string.upload_failed_retry);
                            break;
                    }
                    uploadLayout.setVisibility(View.VISIBLE);
                    break;
                default:
                    uploadLayout.setVisibility(View.INVISIBLE);
                    break;
            }

            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    statusTv.setText(R.string.not_published);
                    statusTv.setTextColor(0xff333333);
                    break;
                case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    statusTv.setText(R.string.status_transcoding);
                    statusTv.setTextColor(0xff333333);
                    break;
                case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    statusTv.setText(R.string.in_review);
                    statusTv.setTextColor(0xff333333);
                    break;
                case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    statusTv.setText(R.string.published);
                    statusTv.setTextColor(0xff333333);
                    break;
                case PublishUtil.PROGRESS_STATUS_REJECT:
                    statusTv.setText(R.string.reject);
                    statusTv.setTextColor(0xfff22446);
                    break;
            }
            Glide.with(itemView.getContext())
                    .load(WebImageUrlModifier.bigImage(data.getCoverUrl()))
                    .apply(RequestOptions.placeholderOf(R.drawable.default_image_bg))
                    .into(coverIv);
            episodeTv.setText(String.format(itemView.getContext().getString(R.string.total_episode), data.getVideoNum()));
        }
    }

    private class CancelPublishAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                Moment moment = new Moment();
                moment.setId(getItem(position).getGoodsId());
                Response<ResponseBody> response = ApiManager.getService().changeMomentStatus(moment.getId(), ActionEngine.GET_OFF, moment).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                LearnVideoModel learnVideoModel = getItem(position);
                learnVideoModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED);
                setData(position, learnVideoModel);
            }
        }
    }


    private class DeleteGoodsAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                Response<ResponseBody> response = ApiManager.getService().deleteMoment(getItem(position).getGoodsId()).execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                remove(position);
            }
        }
    }

    public class SubmitReviewAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            position = (int) objects[0];
            String goodsId = getItem(position).getGoodsId();
            List guaranteeItemList = (List) objects[1];
            List<Guarantee> guaranteeList = new LinkedList<>();
            for (Object item : guaranteeItemList) {
                GuaranteeItem guaranteeItem = (GuaranteeItem) item;
                Guarantee guarantee = new Guarantee();
                guarantee.setId(guaranteeItem.getId());
                guarantee.setName(guaranteeItem.getTitle());
                guarantee.setDetail(guaranteeItem.getContent());
                guaranteeList.add(guarantee);
            }
            Moment moment = new Moment();
            moment.setId(goodsId);
            DetailBackup detailBackup = new DetailBackup();
            detailBackup.setGuarantee(guaranteeList);
            moment.setDetailBackup(detailBackup);
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .changeMomentStatus(moment.getId(), ActionEngine.PUT_ON, moment)
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    LearnVideoModel learnVideoModel = getItem(position);
                    UpdateBuilder<LearnVideoModel, String> updateBuilder = LearnVideoModelDao.getDao().updateBuilder();
                    updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW);
                    updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                    updateBuilder.update();
                    learnVideoModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_IN_REVIEW);
                    setData(position, learnVideoModel);
                } catch (Exception e) {
                    Timber.e("onPostExecute:" + Log.getStackTraceString(e));
                }
            }
        }
    }

    public class EditAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        Activity activity;

        public EditAsyncTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            position = (Integer) objects[0];
            LearnVideoModel learnVideoModel = getItem(position);
            String goodsId = learnVideoModel.getGoodsId();
            try {
                String coverUrl = DownloadUtil.downloadCover(getItem(position).getCoverUrl());
                Response<ResponseBody> response = ApiManager.getService().getMoment(goodsId).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Moment moment = new Moment(JSON.parseObject(json, Moment.class));
                List<TagBackup> tagBackupList = moment.getTags();
                CourseTypeItem courseTypeItem = CourseTypeItem.newBuilder().build();
                SelectSuitablePeopleItem selectSuitablePeopleItem = SelectSuitablePeopleItem.newBuilder().build();
                List<SelectLearnTargetItem> selectLearnTargetItemList = new LinkedList<>();
                List<SelectTagItem> selectTagItemList = new LinkedList<>();
                TeacherItem teacherItem = TeacherItem.newBuilder().build();
                PublishInterestItem publishInterestItem = PublishInterestItem.newBuilder().build();
                publishInterestItem.setParent(PublishIndustryItem.newBuilder().build());
                for (TagBackup tagBackup : tagBackupList) {
                    if (tagBackup == null) continue;
                    switch (tagBackup.getGroupType()) {
                        case SetupUtil.GROUP_TYPE_TEACHER:
                            teacherItem.setId(tagBackup.getId());
                            teacherItem.setTitle(tagBackup.getName());
                            break;
                        case SetupUtil.GROUP_TYPE_CATEGORY:
                            publishInterestItem.setId(tagBackup.getId());
                            publishInterestItem.setTitle(tagBackup.getName());
                            publishInterestItem.setParent(PublishIndustryItem.newBuilder()
                                    .id(tagBackup.getSubGroupType())
                                    .title(tagBackup.getSubGroupName())
                                    .build());
                            break;
                        case SetupUtil.GROUP_TYPE_COURSE_TYPE:
                            courseTypeItem.setId(tagBackup.getId());
                            courseTypeItem.setTitle(tagBackup.getName());
                            break;
                        case SetupUtil.GROUP_TYPE_SUITABLE_PEOPLE:
                            selectSuitablePeopleItem.setId(tagBackup.getId());
                            selectSuitablePeopleItem.setTitle(tagBackup.getName());
                            break;
                        case SetupUtil.GROUP_TYPE_LEARN_TARGET:
                            selectLearnTargetItemList.add(SelectLearnTargetItem.newBuilder()
                                    .id(tagBackup.getId())
                                    .title(tagBackup.getName())
                                    .build());
                            break;
                        case SetupUtil.GROUP_TYPE_OTHER:
                            selectTagItemList.add(SelectTagItem.newBuilder()
                                    .id(tagBackup.getId())
                                    .name(tagBackup.getName())
                                    .build());
                            break;
                    }
                }
                List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
                List<Guarantee> guaranteeList = moment.getDetailBackup().getGuarantee();
                for (Guarantee guarantee : guaranteeList) {
                    guaranteeItemList.add(GuaranteeItem.newBuilder()
                            .id(guarantee.getId())
                            .title(guarantee.getName())
                            .content(guarantee.getDetail())
                            .build());
                }
                List<PublishLearnVideoItem> publishLearnVideoItemList = new LinkedList<>();
                VideoCourse videoCourse = JsonUtil.toObject(moment.getMoreBackup(), VideoCourse.class);
                List<SingleVideo> singleVideoList = videoCourse.getVideos();

                for (SingleVideo singleVideo : singleVideoList) {
                    publishLearnVideoItemList.add(PublishLearnVideoItem.newBuilder()
                            .preUpload(true)
                            .coverUrl(singleVideo.getCover())
                            .duration(singleVideo.getDuration())
                            .size(singleVideo.getSize())
                            .trail(singleVideo.getFree() == 1)
                            .videoUrl(singleVideo.getUrl())
                            .title(singleVideo.getTitle())
                            .build());
                }

                return PublishLearnVideoFormModel.newBuilder()
                        .operationType(PublishUtil.OPERATION_TYPE_EDIT)
                        .courseIntroduction(moment.getSummary())
//                        .courseTypeItem(courseTypeItem)
//                        .selectSuitablePeopleItem(selectSuitablePeopleItem)
//                        .selectLearnTargetItemList(selectLearnTargetItemList)
                        .coverUrl(coverUrl)
                        .goodsId(moment.getId())
                        .price(String.valueOf(moment.getCommodityBackup().getPrice()))
                        .platformDividend(videoCourse.getDivisionProportion() == null ? "" : StringUtils.priceFormatEscapeRedundantTailZero(videoCourse.getDivisionProportion() * 100))
                        .priceId(videoCourse.getApplePriceId())
                        .title(moment.getTitle())
//                        .selectTagItemList(selectTagItemList)
                        .publishLearnVideoItemList(publishLearnVideoItemList)
//                        .publishInterestItem(publishInterestItem)
//                        .selectTagItemList(selectTagItemList)
                        .selectGuaranteeItemList(guaranteeItemList)
//                        .teacherItem(teacherItem)
                        .build();
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else if (o instanceof PublishLearnVideoFormModel) {
                ARouter.getInstance()
                        .build(ARouterConfig.PublishLearnVideoPage)
                        .withParcelable("formModel", (Parcelable) o)
                        .navigation(activity, MerchandiseManagementPage.REQUEST_CODE_PUBLISH);
            } else {
                ToastX.show(R.string.unknown_error);
            }
        }
    }
}
